package com.fingard.dsp.bank.directbank.chinapay05;

import com.chinapay.secss.SecssConstants;
import com.chinapay.secss.SecssUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.directbank.chinapay01.util.SDKUtil;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 上海银联单笔实时代扣
 * 
 * @author Cruise
 * @date 2019/5/21
 */
public class ChinaPay05RealTime extends ChinaPay05Base implements IRealTime {
	@Override
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
			if (actItem == null) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = "未找到账号[" + p_req9108.singleDetail.recAct + "]商户配置信息!";
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = FailCode.E9981;
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}

			Map<String, String> tmpRealTimeRequest = new HashMap<String, String>();

			tmpRealTimeRequest.put("Version", "20150922");
			tmpRealTimeRequest.put("AccessType", "0");
			tmpRealTimeRequest.put("InstuId", "");
			tmpRealTimeRequest.put("AcqCode", "");
			tmpRealTimeRequest.put("MerId", actItem.merchantId);
			tmpRealTimeRequest.put("MerOrderNo", p_req9108.singleDetail.askNumber);
			tmpRealTimeRequest.put("TranDate", Format.Date8Format.format(p_req9108.singleDetail.getPayDateTime()));
			tmpRealTimeRequest.put("TranTime", Format.Time6Format.format(p_req9108.singleDetail.getPayDateTime()));
			tmpRealTimeRequest.put("OrderAmt", StringHelper.amountMultiply100(p_req9108.singleDetail.payAmount));
			tmpRealTimeRequest.put("TranType", "0004");
			tmpRealTimeRequest.put("BusiType", "0001");
			tmpRealTimeRequest.put("CurryNo", "CNY");
			tmpRealTimeRequest.put("SplitType", "");
			tmpRealTimeRequest.put("SplitMethod", "");
			tmpRealTimeRequest.put("MerSplitMsg", "");
			tmpRealTimeRequest.put("BankInstNo", "");
			tmpRealTimeRequest.put("MerPageUrl", "");
			tmpRealTimeRequest.put("MerBgUrl", actItem.notifyURL);
			tmpRealTimeRequest.put("CommodityMsg", p_req9108.singleDetail.description);
			tmpRealTimeRequest.put("MerResv", p_req9108.singleDetail.attach);

			JSONObject cardTranData = new JSONObject();
			cardTranData.put("CardNo", p_req9108.singleDetail.payAct);
			String cardType = "";
			if ("1".equals(p_req9108.singleDetail.cardType)) {
				cardType = "06";
			} else if ("3".equals(p_req9108.singleDetail.cardType)) {
				cardType = "02";
			} else {
				cardType = "01";
			}
			cardTranData.put("AccType", cardType);
			cardTranData.put("AccName", p_req9108.singleDetail.payName);
			cardTranData.put("CertType", convertCertTypeToBank(p_req9108.singleDetail.certType));
			cardTranData.put("CertNo", p_req9108.singleDetail.certNum);
			cardTranData.put("MobileNo", p_req9108.singleDetail.cellPhone);

			String strCardTranData = cardTranData.toString();
			WriteBankLogLn("加密前的卡保留域:" + strCardTranData);
			strCardTranData = Base64.encodeBase64String(strCardTranData.getBytes(getCharset()));
			SecssUtil secssUtil = getSecssUtil(actItem);
			secssUtil.encryptData(strCardTranData);
			if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
				strCardTranData = secssUtil.getEncValue();
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = secssUtil.getErrCode() + "+" + secssUtil.getErrMsg();
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			tmpRealTimeRequest.put("CardTranData", strCardTranData);
			tmpRealTimeRequest.put("Term", "");
			tmpRealTimeRequest.put("PayTimeOut", "");
			tmpRealTimeRequest.put("TimeStamp", "");
			tmpRealTimeRequest.put("RemoteAddr", "");
			tmpRealTimeRequest.put("RiskData", "");
			tmpRealTimeRequest.put("Signature", "");
			
			Map<String, String> sendMap = new TreeMap<String, String>();
			Iterator<String> iterator = tmpRealTimeRequest.keySet().iterator();
			while(iterator.hasNext()) {
				String key = iterator.next();
				String value = tmpRealTimeRequest.get(key);
				
				if (key.startsWith("__")) {
                    continue;
                }
                // 过滤空字段
                if (StringHelper.isNullOrEmpty(value)) {
                    continue;
                }
                sendMap.put(key, value);
			}
			WriteBankLogLn2("单笔代扣提交请求数据:\r\n" + SDKUtil.coverMap2String(sendMap));
			secssUtil.sign(sendMap);
			if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
				sendMap.put("Signature", secssUtil.getSign());
				Map<String, String> tmpMapRet = sendDataToBank(sendMap, bankFront.getUrl("9108"));
				if (tmpMapRet.size() > 0) {
					tmpRetDetail.respCode = "0";
					tmpRetDetail.respInfo = tmpMapRet.get("respMsg");
					tmpRetDetail.transState = tmpMapRet.get("respCode");
					tmpRetDetail.payInfoCode = tmpMapRet.get("respCode");
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = "银行响应数据为空!";
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "签名失败:" + secssUtil.getErrMsg();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req9144.askNumber;

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
			if (actItem != null) {
				Map<String, String> tmpQryRequest = new HashMap<String, String>();

				tmpQryRequest.put("Version", "20140728");
				tmpQryRequest.put("AccessType", "0");
				tmpQryRequest.put("InstuId", "");
				tmpQryRequest.put("MerId", actItem.merchantId);
				tmpQryRequest.put("MerOrderNo", p_req9144.askNumber);
				tmpQryRequest.put("TranDate", Format.Date8Format.format(p_req9144.getBgnDateTime()));
				tmpQryRequest.put("TranType", "0502");
				tmpQryRequest.put("BusiType", "0001");
				
				JSONObject transReserveJson = new JSONObject();
				transReserveJson.put("BizType", "");
				transReserveJson.put("SubTransType", "99100001");
				transReserveJson.put("TerminalType", "08");
				transReserveJson.put("AcctInTp", "");
				transReserveJson.put("MiniPayUrl", "");
				transReserveJson.put("MiniPayFlag", "");
				transReserveJson.put("DeviceMerId", "");
				tmpQryRequest.put("TranReserved", transReserveJson.toString());
				tmpQryRequest.put("Signature", "");
				
				Map<String, String> sendMap = new TreeMap<String, String>();
				Iterator<String> iterator = tmpQryRequest.keySet().iterator();
				while(iterator.hasNext()) {
					String key = iterator.next();
					String value = tmpQryRequest.get(key);
					
					if (key.startsWith("__")) {
	                    continue;
	                }
	                // 过滤空字段
	                if (StringHelper.isNullOrEmpty(value)) {
	                    continue;
	                }
	                sendMap.put(key, value);
				}

				WriteBankLogLn2("单笔代扣查询请求数据:\r\n" + SDKUtil.coverMap2String(sendMap));
				SecssUtil secssUtil = getSecssUtil(actItem);
				secssUtil.sign(sendMap);

				if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
					tmpQryRequest.put("Signature", secssUtil.getSign());

					Map<String, String> tmpMapRet = sendDataToBank(tmpQryRequest, bankFront.getUrl("9144"));
					if (tmpMapRet.size() > 0) {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.respInfo = tmpMapRet.get("respMsg");
						String transStatus = tmpMapRet.get("OrderStatus");
						if (StringHelper.isNullOrEmpty(transStatus)) {
							transStatus = tmpMapRet.get("respCode");
						}
						if(transStatus.equals("2004")){
							tmpRetDetail.respCode = "-1";
						}
						tmpRetDetail.transState = transStatus;
						tmpRetDetail.payInfoCode = transStatus;
					} else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "银行响应数据为空!";
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = "签名失败:" + secssUtil.getErrMsg();
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "未找到账号:[" + p_req9144.recAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
